var express = require('express');
var router = express.Router();
let upload = require('../util/multer/index')
var moment = require('moment');
const rp = require('request-promise-native');
let { getBase64, setBase64, isgender, getMOvieList, formateDate, urlf2z, getPerformerAll, FormatData } = require('../util.js');
let { GetopenID_Url, appId, AppSecret } = require('../config');
let { isUser, addUser, updataUser, GetUsersById, getMovietype, getMovieTypeCount, getMovieListUser, getMovieById, getCommentAll, getHotCommentById,
  getNewCommentById, addComment, getPerformerById, addRelation, isaddRelation, updataRelation, isaddPraise, delPraise, addPraise, changecommentPraise,
  isaaddFollow, delFollow, addFollow, getFollowCommmentById, getCommentById, getCommList, addComm, getSeenMovie, getWantMovie, getHotList,
  getUserCommentById, getCommentBymovieId, upDataCommentScore, getNewsList, GetnewsById, isCollection, delCollection, addCollection, changeNewsReading
} = require('../mysql/users')
/**
 * 所有关于用户的请求接口
 */
const methodsToken = [
  '/userInfoInit',
  '/userInfoById',
  '/addComment',
  '/addRelation',
  '/getMovieById',
  '/addPraise',
  '/addFollow',
  '/getFollowCommmentById',
  '/getCommentById',
  '/addComm',
  '/getSeenMovie',
  '/getWantMovie',
  '/getUserCommentById',
  '/addCollection'
];
router.post("*", (req, res, next) => {
  // 判断token是否存在
  if (methodsToken.indexOf(req.url) >= 0) {
    // 获取用户token
    let userToken = req.body.userToken;
    if (!userToken) {
      return res.json({
        code: 0,
        data: "请先登录"
      });
    } else {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  } else {
    let userToken = req.body.userToken;
    if (userToken) {
      let userId = setBase64(userToken);
      req.body.userId = userId;
    }
  }
  next();
})
/**
 *  获取openid
 */
router.post('/login', async (req, res, next) => {
  let url = `${GetopenID_Url}appid=${appId}&secret=${AppSecret}&js_code=${req.body.code}&grant_type=authorization_code`;
  let userCode = await rp({
    method: 'GET', url, json: true
  })
  let isUserInfo = await isUser({
    openid: userCode.openid
  })
  if (isUserInfo.length) {
    res.json({
      code: 1,
      data: {
        Token: getBase64(isUserInfo[0].userId)
      }
    })
  } else {
    let data = await addUser({
      openid: userCode.openid,
      session_key: userCode.session_key
    })
    res.json({
      code: 1,
      data: {
        Token: getBase64(data.insertId)
      }
    })
  }
});
/**
 *   修改初始信息并返回用户信息
 */
router.post('/upinfoLogin', async (req, res, next) => {
  let { nickName, gender, country, avatarUrl, userId, Token } = req.body;
  userId = setBase64(Token)
  await updataUser(userId, {
    userName: nickName,
    userSex: isgender(gender),
    userCountry: country,
    userUrl: avatarUrl
  })
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 同步用户数据
 */
router.post('/userInfoInit', async (req, res, next) => {
  let { nickName, gender, country, avatarUrl, userId } = req.body;
  await updataUser(userId, {
    userName: nickName,
    userSex: isgender(gender),
    userCountry: country,
    userUrl: avatarUrl
  })
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 返回用户信息
 */
router.post('/userInfoById', async (req, res, next) => {
  let { userId } = req.body;
  let data = await GetUsersById(userId);
  res.json({
    code: 1,
    data
  })
})
/**
 * 返回首页数据
 */
router.get('/getmovieListData', async (req, res, next) => {
  let [hotMovie, soonMovie, topMovie] = await getMovietype();
  hotMovie = getMOvieList(hotMovie);
  soonMovie = getMOvieList(soonMovie);
  topMovie = getMOvieList(topMovie);
  res.json({
    code: 1,
    hotMovie, soonMovie, topMovie
  })
})
/**
 * 获取不同类型的电影（分页处理）
 */
router.post('/getMovieByType', async (req, res, next) => {
  let { page, limit, type, movieName } = req.body;
  let count = await getMovieTypeCount({
    movieType: type,
    movieName: movieName
  });
  let pageNum = Math.ceil((count / limit));
  if (page > pageNum) {
    return res.json({
      code: 0,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * limit;
  let data = await getMovieListUser(num, limit, {
    movieType: type,
    movieName: movieName
  });
  data.data.forEach(item => {
    item.movieTime = formateDate(item.movieTime)
    item.movieImgList = JSON.parse(item.movieImgList)
    item.movietag = JSON.parse(item.movietag);
  })
  res.json({
    code: 1,
    data: data.data,
    count: data.count
  })
})
/**
 * 获取指定id的电影信息
 */
router.post('/getMovieById', async (req, res, next) => {
  let { movieId, userId } = req.body;
  let movie = await getMovieById(movieId);
  let performerList = await getPerformerAll(JSON.parse(movie[0].performerList), getPerformerById)
  let relationType = await isaddRelation({ userId, movieId })
  if (relationType.length) {
    relationType = relationType[0].relationType;
  } else {
    relationType = '';
  }
  movie[0].relationType = relationType;
  movie[0].performerList = performerList;
  movie[0].movieTime = formateDate(movie[0].movieTime)
  movie[0].movieImgList = JSON.parse(movie[0].movieImgList)
  movie[0].movietag = JSON.parse(movie[0].movietag);
  res.json({
    code: 1,
    data: {
      movie
    }
  })
})
/**
 * 获取热门评论
 */
router.post('/getHotCommentById', async (req, res, next) => {
  let { movieId } = req.body;
  let comment = await getHotCommentById(movieId);
  comment.forEach(item => {
    item.commentTime = formateDate(item.commentTime);
    item.commentImgList = JSON.parse(item.commentImgList)
  })
  res.json({
    code: 1,
    comment
  })
})
/**
 * 获取最新的评论
 */
router.post('/getNewCommentById', async (req, res, next) => {
  let { movieId, page, limit } = req.body;
  var num = (page - 1) * limit;
  let comment = await getNewCommentById(num, limit, movieId);
  if (comment.length == 0) {
    return res.json({
      code: 0,
      comment: "数据已经加载完毕"
    });
  } else {
    comment.forEach(item => {
      item.commentTime = formateDate(item.commentTime);
      item.commentImgList = JSON.parse(item.commentImgList)
    })
    return res.json({
      code: 1,
      comment: comment
    });
  }
})
/**
 * 获取关注的人的评论
 */
router.post('/getFollowCommmentById', async (req, res, next) => {
  let { movieId, page, limit, userId } = req.body;
  var num = (page - 1) * limit;
  let comment = await getFollowCommmentById(num, limit, movieId, userId);
  if (comment.length == 0) {
    return res.json({
      code: 0,
      comment: "数据已经加载完毕"
    });
  } else {
    comment.forEach(item => {
      item.commentTime = formateDate(item.commentTime);
      item.commentImgList = JSON.parse(item.commentImgList)
    })
    return res.json({
      code: 1,
      comment: comment
    });
  }
})
/**
 * 获取自己的评论
 */
router.post('/getUserCommentById', async (req, res, next) => {
  let { movieId, userId } = req.body;
  let comment = await getUserCommentById(movieId, userId);
  comment.forEach(item => {
    item.commentTime = formateDate(item.commentTime);
    item.commentImgList = JSON.parse(item.commentImgList)
  })
  res.json({
    code: 1,
    comment
  })
})
/**
 * 发表评论
 */
router.post('/addComment', async (req, res, next) => {
  let { commentTitle, userId, commentCom, movieId, commentScore, commentImgList } = req.body;
  await addComment({ commentTitle, userId, commentCom, movieId, commentScore, commentImgList });
  let comment = await getCommentBymovieId(movieId);
  const sum = Math.ceil(comment.reduce(
    (accumulator, currentValue) => {
      return accumulator + Number(currentValue.commentScore)
    }
    , 0) / comment.length);
  await upDataCommentScore({
    movieScore: sum
  }, movieId)
  res.json({
    code: 1,
    data: "添加成功"
  })
})
/**
 * 用户选择电影的情况
 */
router.post('/addRelation', async (req, res, next) => {
  let { userId, relationType, movieId } = req.body;
  let flog = await isaddRelation({
    userId, movieId
  })
  if (flog.length) {
    await updataRelation(flog[0].relationId, {
      relationType
    })
    res.json({
      code: 1,
      data: "修改成功"
    })
  } else {
    await addRelation({
      userId, relationType, movieId
    })
    res.json({
      code: 1,
      data: "添加成功"
    })
  }
})
/**
 * 点赞
 */
router.post('/addPraise', async (req, res, next) => {
  let { userId, commentId } = req.body;
  let flog = await isaddPraise({
    userId, commentId
  })
  if (flog.length) {
    console.log(flog)
    await delPraise(flog[0].praiseId)
    await changecommentPraise({
      PraiseNum: -1,
      commentId
    })
    res.json({
      code: 1,
      data: {
        info: "取消点赞成功",
        flog: 0
      }
    })
  } else {
    await addPraise({
      userId, commentId
    })
    await changecommentPraise({
      PraiseNum: 1,
      commentId
    })
    res.json({
      code: 1,
      data: {
        info: "点赞成功",
        flog: 0
      }
    })
  }
})
/**
 * 关注
 */
router.post('/addFollow', async (req, res, next) => {
  let { userId, touserId } = req.body;
  let flog = await isaaddFollow({
    userId, touserId
  })
  if (flog.length) {
    await delFollow(flog[0].followId)
    res.json({
      code: 1,
      data: {
        info: "取消关注成功",
        flog: 0
      }
    })
  } else {
    await addFollow({
      userId, touserId
    })
    res.json({
      code: 1,
      data: {
        info: "关注成功",
        flog: 0
      }
    })
  }
})
/**
 * 获取指定评论信息
 */
router.post('/getCommentById', async (req, res, next) => {
  let { commentId, touserId, userId } = req.body;
  let data = await getCommentById(commentId);
  let Follow = await isaaddFollow({
    userId, touserId
  })
  let Praise = await isaddPraise({
    userId, commentId
  })
  data[0].isCollection = Boolean(Follow.length)
  data[0].isFabulous = Boolean(Praise.length)
  data[0].commentTime = formateDate(data[0].commentTime)
  data[0].commentImgList = JSON.parse(data[0].commentImgList)
  res.json({
    code: 1,
    data: data
  })
})
/**
 * 获取二级评论
 */
router.post('/getCommList', async (req, res, next) => {
  let { commentId, page, limit } = req.body;
  var num = (page - 1) * limit;
  let data = await getCommList(num, limit, commentId)
  if (data.length == 0) {
    return res.json({
      code: 0,
      data: "数据已经加载完毕"
    });
  } else {
    data.forEach(item => {
      item.comentTime = formateDate(item.comentTime)
    })
    return res.json({
      code: 1,
      data: data
    });
  }
})
/**
 * 发表评论
 */
router.post('/addComm', async (req, res, next) => {
  let { commentId, userId, comentCom } = req.body;
  await addComm({ commentId, userId, comentCom });
  res.json({
    code: 1,
    data: "添加成功"
  })
})
/**
 * 获取用户看过的电影
 */
router.post('/getSeenMovie', async (req, res, next) => {
  let { userId } = req.body;
  let data = await getSeenMovie(userId)
  data.forEach(item => {
    item.movieTime = formateDate(item.movieTime)
    item.movieImgList = JSON.parse(item.movieImgList)
    item.movietag = JSON.parse(item.movietag);
    item.relationTime = formateDate(item.relationTime);
  })
  res.json({
    code: 1,
    data
  })
})
/**
 * 获取用户想看的电影
 */
router.post('/getWantMovie', async (req, res, next) => {
  let { userId } = req.body;
  let data = await getWantMovie(userId)
  data.forEach(item => {
    item.movieTime = formateDate(item.movieTime)
    item.movieImgList = JSON.parse(item.movieImgList)
    item.movietag = JSON.parse(item.movietag);
    item.relationTime = formateDate(item.relationTime);
  })
  res.json({
    code: 1,
    data
  })
})
/**
 * 获取用户热搜
 */
router.post('/getHotList', async (req, res, next) => {
  let data = await getHotList();
  res.json({
    code: 1,
    data
  })
})
/**
 * 获取新闻
 */
router.post('/getNewsList', async (req, res, next) => {
  let { page, limit } = req.body;
  var num = (page - 1) * limit;
  let data = await getNewsList(num, limit, {

  })
  if (data.data.length == 0) {
    return res.json({
      code: 0,
      data: "数据已经加载完毕"
    });
  } else {
    return res.json({
      code: 1,
      data: FormatData(data.data, {
        newsImgSrc: 'json',
        newsTime: 'date'
      }),
    });
  }
})
/**
 * 获取新闻详情
 */
router.post('/getNewsInfo', async (req, res, next) => {
  let { newsId, userId } = req.body;
  let [data] = await GetnewsById(newsId);
  await changeNewsReading({
    newsId: newsId, newsReading: 1
  })
  if (userId) {
    let collection = await isCollection({
      userId, newsId
    })
    data.collection = Boolean(collection.length)
  } else {
    data.collection = false
  }
  res.json({
    code: 1,
    data: FormatData(data, {
      newsImgSrc: 'json',
      newsTime: 'date'
    })
  })
})
/**
 * 收藏
 */
router.post('/addCollection', async (req, res, next) => {
  let { userId, newsId } = req.body;
  let flog = await isCollection({
    userId, newsId
  })
  if (flog.length) {
    await delCollection(flog[0].collectionId)
    res.json({
      code: 1,
      data: {
        info: "取消收藏成功",
        flog: 0
      }
    })
  } else {
    await addCollection({
      userId, newsId
    })
    res.json({
      code: 1,
      data: {
        info: "收藏成功",
        flog: 1
      }
    })
  }
})
/**
 * 图片文件上传处理
 */
router.post('/uploadImg', upload.single('file'), async (req, res, next) => {
  let url = `${req.protocol}://${req.headers.host}/${req.file.path}`;
  res.json({
    code: 1,
    url: urlf2z(url)
  })
})

module.exports = router;
